package com.mxf.agricultural.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mxf.agricultural.annotation.AuthCheck;
import com.mxf.agricultural.common.BaseResponse;
import com.mxf.agricultural.common.DeleteRequest;
import com.mxf.agricultural.common.ErrorCode;
import com.mxf.agricultural.common.ResultUtils;
import com.mxf.agricultural.constant.UserConstant;
import com.mxf.agricultural.exception.BusinessException;
import com.mxf.agricultural.exception.ThrowUtils;
import com.mxf.agricultural.model.dto.account.AccountAddRequest;
import com.mxf.agricultural.model.dto.account.AccountEditRequest;
import com.mxf.agricultural.model.dto.account.AccountQueryRequest;
import com.mxf.agricultural.model.entity.Account;
import com.mxf.agricultural.model.entity.User;

import com.mxf.agricultural.service.AccountService;
import com.mxf.agricultural.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 贷款接口
 *
 */
@RestController
@RequestMapping("/account")
@Slf4j
public class AccountController {

    @Resource
    private AccountService accountService;

    @Resource
    private UserService userService;

    @PostMapping("/ok")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> ok(@RequestBody AccountEditRequest accountEditRequest) {
        if (accountEditRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Account account = new Account();
        account.setId(accountEditRequest.getId());
        account.setIsok(1);
        boolean result = accountService.updateById(account);
        if (result) {
            User user = userService.getById(accountEditRequest.getUserid());
            User userNew = new User();
            userNew.setId(accountEditRequest.getUserid());
            userNew.setBalance(user.getBalance()+ accountEditRequest.getBalance());
            boolean resultNew = userService.updateById(userNew);
        }
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 创建
     *
     * @param accountAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addAccount(@RequestBody AccountAddRequest accountAddRequest, HttpServletRequest request) {
        if (accountAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Account account = new Account();
        BeanUtils.copyProperties(accountAddRequest, account);

        account.setIsok(0);

        boolean result = accountService.save(account);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newAccountId = account.getId();
        return ResultUtils.success(newAccountId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteAccount(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Account oldAccount = accountService.getById(id);
        ThrowUtils.throwIf(oldAccount == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldAccount.getUserid().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = accountService.removeById(id);
        return ResultUtils.success(b);
    }


    /**
     * 分页获取列表（仅管理员）
     *
     * @param accountQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Account>> listAccountByPage(@RequestBody AccountQueryRequest accountQueryRequest, HttpServletRequest request) {
        User user = userService.getLoginUser(request);
//        if(!Objects.equals(user.getUserRole(), UserConstant.ADMIN_ROLE)){
//            return ResultUtils.success(null);
//        }
        long current = accountQueryRequest.getCurrent();
        long size = accountQueryRequest.getPageSize();
        Page<Account> accountPage = accountService.page(new Page<>(current, size),
                accountService.getQueryWrapper(accountQueryRequest));
        return ResultUtils.success(accountPage);
    }

    /**
     * 编辑
     *
     * @param accountEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editAccount(@RequestBody AccountEditRequest accountEditRequest, HttpServletRequest request) {
        if (accountEditRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Account account = new Account();
        BeanUtils.copyProperties(accountEditRequest, account);

        User loginUser = userService.getLoginUser(request);
        long id = accountEditRequest.getId();
        // 判断是否存在
        Account oldAccount = accountService.getById(id);
        ThrowUtils.throwIf(oldAccount == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldAccount.getUserid().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = accountService.updateById(account);
        return ResultUtils.success(result);
    }

}
